

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class MsgSender {

	public static void main(String[] args)  {
		// 初始化连接工厂
		ConnectionFactory connfactory = new ConnectionFactory();
		//设置连接工厂指向的目的地
		connfactory.setHost("localhost");
        //通过工厂创建消息连接		
		Connection conn = null;
		Channel channel = null;
		try {
			conn = connfactory.newConnection();
			// 通过消息连接创建通讯通道
			channel = conn.createChannel();
			String qName = "MyQueue";
			// 通过通道创建一个队列
			channel.queueDeclare(qName, false, false, false, null);
			//定义消息
			String message = "This is my First Msg By RabbitMQ";
			// 发送消息
			channel.basicPublish("", qName, null, message.getBytes());
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TimeoutException e) {
			e.printStackTrace();
		}
		finally{
			// 关闭通道和连接
		    try {
		    	if(channel != null){
		    		channel.close();	
		    	}
				if(conn != null)
				{
					conn.close();	
				}			    
			} catch (IOException e) {
				e.printStackTrace();
			} catch (TimeoutException e) {
				e.printStackTrace();
			}			
		}
	}
}
